<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>否决报障</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">

		<!--标准mui.css-->
		<link rel="stylesheet" href="../css/mui.min.css">
		<link rel="stylesheet" type="text/css" href="../css/mui.picker.min.css" />
		<!--App自定义的css-->
		<link rel="stylesheet" type="text/css" href="../css/common.css"/>
		<style>
			.mt-1{
				margin-top: 1rem;
			}
			img{
				width: 24%;
				padding-left: 2%; 
			}
			.my-display{
				display: inline;
			}
			.imgDiv{
				position: relative;
				display: inline; 
			}
			.imgDiv .delete {
				position: absolute; 
				right: 1%;
			}
			textarea{
				width: 70%;
				margin-bottom: 0;
				padding: 0 .3rem;
			}
		</style>
	</head>
	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title">否决报障</h1>
		</header>
		<div class="mui-content">
			<div class="mui-collapse-content">
				<ul class="item-flashing">
					<li class="item-weight">
						<label for="">设备名称</label>
						<span id="device_name"></span>
					</li>
					<li class="item-weight">
						<label for="" style="float: left;">故障描述</label>
						<textarea id="desc" class="mt-1" rows="3" placeholder="请输入故障描述"></textarea>
					</li>
					<li class="item-weight">
						<div class="mui-collapse-content mt-1" id="descImg">
							<input type="file" accept="image/*" id="addImg" onchange="showPreview(this)" style="display: none;">
							<img src="../images/iconfont-tianjia.png" id="select" onclick="selectImg()"/>
						</div>
					</li>
				</ul>
			</div>
			<div class="btn-box">
				<button type="button" class="mui-btn mui-btn-primary" id="confirm">完成</button>
			</div>
		</div>
		<script src="../js/mui.min.js"></script>
		<script src="../js/app.js"></script>
		<script src="../js/md5.js"></script>
		<script src="../js/jquery.js"></script>
		<script type="text/javascript">
			mui.init({
				swipeBack:true //启用右滑关闭功能
			});
			
			//获取父页面传值
			var key = 'udacs!@#';//固定的key值
			var mobile = localStorage.getItem('mobile');		
			var warning_Detail = JSON.parse(localStorage.getItem('warning_Detail'));
			var w_id = warning_Detail.id;
			var desc = warning_Detail.desc;
			var device_name = warning_Detail.device_name;
			var mediaID = warning_Detail.mediaID;
			document.getElementById('desc').value = desc;
			document.getElementById('device_name').innerText = device_name;
			for(var i=0;i<mediaID.length;i++){
				$("#select").before('<div class="imgDiv"><img src="'+httpUrl+'download?mediaId='+mediaID[i]+'" data-id="'+i+'"/><img src="../images/delete.png" class="delete" onclick="deleteImg(this)"/></div>');
				if(i==3){
					$('#select').hide();	
				}
			}			
			
			//生成年月日时分秒
			function formatDateTime(type,time) {    
				if(time){
					var date = new Date(time);
				}else{
					var date = new Date();  
				}
			    var y = date.getFullYear();    
			    var m = date.getMonth() + 1;    
			    m = m < 10 ? ('0' + m) : m;    
			    var d = date.getDate();    
			    d = d < 10 ? ('0' + d) : d;    
			    var h = date.getHours();  
			    h = h < 10 ? ('0' + h) : h;  
			    var minute = date.getMinutes();  
			    var second = date.getSeconds();  
			    minute = minute < 10 ? ('0' + minute) : minute;    
			    second = second < 10 ? ('0' + second) : second;
			    if(type === 'date'){
			    	return y+'-'+ m +'-'+d+' '+h+':'+minute+':'+second;    
			    }else{
		    		return y+''+ m +''+d +''+h+''+minute+''+second;   
		    	}
			};
				
			//完成按钮操作
	        mui(".btn-box").on('tap','.mui-btn-primary',function(){
	        	if(imgFile.length == 0){
	        		editWarning();
	        	}else{
	        		uploadAllImg();	//上传所有图片后再提交修改报障请求
	        	}
	        	
	        })
	        
	        //修改报障信息
	        function editWarning(){
				var timestamp = formatDateTime();//年月日时分秒
				var token = mobile + timestamp + key;//token的拼接
				var md5 = hex_md5(token);//token的ma5加密
	        	desc = document.getElementById('desc').value;
				$.ajax(httpUrl+'edit_warning',{
					data:JSON.stringify({
						"auth":{ 
							"mobile":mobile,
							"token":md5,
							"imei":"imei",
							"imsi":"imsi",
							"timestamp" :timestamp
						},
				   		"api_ver":"1",
						"req":{
							"w_id": w_id,
							"desc": desc,
							"media":imgMedia
						}
					}),
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					contentType: "text/plain; charset=utf-8",					
					success:function(data){
						mui.toast('否决成功！',{duration:'2000',type:'div'});
						var Count = localStorage.getItem('warning_Count');
						localStorage.setItem('warning_Count',Count*(-1)); //修改warning_Count使父页面能够监听
						var a = setTimeout(callBack,'2000');
						function callBack(){
							mui.back();
						}
					},
					error:function(xhr,type,errorThrown){
						mui.toast('网络异常或者服务器出错：'+type,{duration:'2000',type:'div'});
					}
				})
			}
	        
	        //点击图片触发文件上传
	        function selectImg(){
	        	$('#addImg').click();
	        }
	        
	        var i = 0; //用来生成图片文件的索引
	        var imgFile=[]; //用来存放添加的图片对象
	        var imgMedia =[]; //用来存放图片上传后返回的mediaid
	        
	        //去除数组中指定项
	        function delItem(arr,val){
	        	for(var i=0; i<arr.length; i++) {
				    if(arr[i] == val) {
				      arr.splice(i, 1);
				      break;
				    }
			  	}
	        }
	        
	        //添加图片
	        function showPreview(source) {
	        	var imgLength = $('img').length;//判断图片的个数，超过4张禁止添加
	        	if(imgLength == 7){
	        		$('#select').hide();	
	        	}else{
	        		$('#select').show();
	        	}
	            var file = source.files[0];
	            if(window.FileReader) {
	                var fr = new FileReader();  
	                fr.onloadend = function(e) {
	                     $("#select").before('<div class="imgDiv"><img src="'+e.target.result+'" data-id="'+i+'"/><img src="../images/delete.png" class="delete" onclick="deleteImg(this)"/></div>');
	                     imgFile.push(file);
	                     i++;
	                };  
	                fr.readAsDataURL(file);  
	            }
	        }
        	
	        //删除图片
	        function deleteImg(obj){
	        	var id = $(obj).prev().attr('data-id');
	        	imgFile.splice(id,1,null);
	        	$(obj).closest('div').remove();
	        	$('#select').show();
	        }
	        
	        //上传图片
	        function uploadImg(img,i) {
	            timestamp = formatDateTime();//年月日时分秒
				token = mobile + timestamp + key;//token的拼接
				md5 = hex_md5(token);//token的ma5加密
				var signature = "fromid:"+mobile+"imei:imei,imsi:imsi,token:"+md5;
				var toUser = 'type:0,id:'+mobile;	//个人
				var Data = new FormData();
				Data.append("signature",signature);
				Data.append("toUser",toUser);
				Data.append("type","1");
				Data.append("mediaDetail","image");
				Data.append("media",img);
				$.ajax(httpUrl+'upload',{	
					data:Data,
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					contentType:false,
					cache:false,	//上传文件不需要缓存
				 	processData: false,	//因为data值是FormData对象，不需要对数据做处理
					success:function(data){
						var media ={};
						media.m_id = data.ret.mediaId;
						imgMedia.push(media);
						console.log("图片"+i+"上传成功！");
						if(i == imgFile.length-1 ){
							editWarning();	//上传最后一张图片成功后调用修改报障接口
						}
					},
					error:function(xhr,type,errorThrown){
						console.log("图片"+i+"上传失败！");
						mui.toast('网络异常或者服务器出错：'+type,{duration:'2000',type:'div'});
					}
				})
		   } 
	        
	        //上传所有图片
	        function uploadAllImg() {
	        	delItem(imgFile,null); //去除相关图片对象
	            for(var i=0;i<imgFile.length;i++){
	            	uploadImg(imgFile[i],i);
	            }
		   } 
		</script>
	</body>
</html>